// components/city-filter/city-filter.js
Component({
  properties: {
    // 是否显示
    visible: {
      type: Boolean,
      value: false
    },
    // 默认选中的地址
    defaultValue: {
      type: Object,
      value: null
    }
  },

  data: {
    // 地址数据
    addressData: [],
    // 省份列表
    provinceList: [],
    // 城市列表
    cityList: [],
    // 区县列表
    districtList: [],
    // 选择器值 [provinceIndex, cityIndex, districtIndex]
    pickerValue: [0, 0, 0],
    // 临时选中的值（确认前）
    tempValue: [0, 0, 0],
    // 当前选中的地址信息
    selectedAddress: null
  },

  lifetimes: {
    attached() {
      this.loadAddressData();
    }
  },

  observers: {
    'visible': function(visible) {
      if (visible) {
        // 显示时，重置为当前选中的值
        if (this.data.selectedAddress) {
          this.setData({
            tempValue: [...this.data.pickerValue]
          });
        }
      }
    }
  },

  methods: {
    // 加载地址数据
    async loadAddressData() {
      try {
        // 导入API方法
        const { getCity } = require('../../api/api.js');
        
        // 调用API获取地址数据
        const res = await getCity();
        
        let addressData = null;
        if (res && res.data) {
          addressData = res.data;
        } else if (res && Array.isArray(res)) {
          addressData = res;
        }
        
        if (addressData && addressData.length > 0) {
          const transformedData = this.transformAddressData(addressData);
          this.setData({ 
            addressData: transformedData,
            provinceList: transformedData
          });
          
          // 初始化列表
          this.updateCityList(0);
          this.updateDistrictList(0, 0);
          
          // 如果有默认值，设置默认选中
          if (this.properties.defaultValue) {
            this.setDefaultValue(this.properties.defaultValue);
          }
        }
      } catch (error) {
        console.error('加载地址数据失败:', error);
      }
    },

    // 转换地址数据格式
    transformAddressData(data) {
      return data.map(province => ({
        v: province.v,
        n: province.n,
        c: province.c.map(city => ({
          v: city.v,
          n: city.n,
          c: city.c.map(district => ({
            v: district.v,
            n: district.n,
            c: []
          }))
        }))
      }));
    },

    // 更新城市列表
    updateCityList(provinceIndex) {
      const { addressData } = this.data;
      if (!addressData || !addressData[provinceIndex]) return;
      
      const province = addressData[provinceIndex];
      this.setData({
        cityList: province.c || []
      });
    },

    // 更新区县列表
    updateDistrictList(provinceIndex, cityIndex) {
      const { addressData } = this.data;
      if (!addressData || !addressData[provinceIndex]) return;
      
      const province = addressData[provinceIndex];
      if (!province.c || !province.c[cityIndex]) return;
      
      const city = province.c[cityIndex];
      this.setData({
        districtList: city.c || []
      });
    },

    // 设置默认值
    setDefaultValue(defaultValue) {
      const { addressData } = this.data;
      if (!addressData || addressData.length === 0) return;

      let provinceIndex = 0;
      let cityIndex = 0;
      let districtIndex = 0;

      // 查找省份索引
      if (defaultValue.province) {
        const foundProvinceIndex = addressData.findIndex(item => item.n === defaultValue.province);
        if (foundProvinceIndex >= 0) {
          provinceIndex = foundProvinceIndex;
          const province = addressData[provinceIndex];
          
          // 查找城市索引
          if (defaultValue.city && province.c) {
            const foundCityIndex = province.c.findIndex(item => item.n === defaultValue.city);
            if (foundCityIndex >= 0) {
              cityIndex = foundCityIndex;
              const city = province.c[cityIndex];
              
              // 查找区县索引
              if (defaultValue.district && city.c) {
                const foundDistrictIndex = city.c.findIndex(item => item.n === defaultValue.district);
                if (foundDistrictIndex >= 0) {
                  districtIndex = foundDistrictIndex;
                }
              }
            }
          }
        }
      }

      this.updateCityList(provinceIndex);
      this.updateDistrictList(provinceIndex, cityIndex);
      
      this.setData({
        pickerValue: [provinceIndex, cityIndex, districtIndex],
        tempValue: [provinceIndex, cityIndex, districtIndex]
      });
      
      this.updateSelectedAddress(provinceIndex, cityIndex, districtIndex);
    },

    // 选择器值变化（滑动过程中）
    onPickerChange(e) {
      const value = e.detail.value;
      const oldValue = this.data.tempValue;
      
      // 检查哪一列发生了变化
      if (value[0] !== oldValue[0]) {
        // 省份变化
        this.updateCityList(value[0]);
        this.updateDistrictList(value[0], 0);
        this.setData({
          tempValue: [value[0], 0, 0]
        });
      } else if (value[1] !== oldValue[1]) {
        // 城市变化
        this.updateDistrictList(value[0], value[1]);
        this.setData({
          tempValue: [value[0], value[1], 0]
        });
      } else {
        // 区县变化
        this.setData({
          tempValue: value
        });
      }
    },

    // 开始滑动
    onPickerStart() {
      // 可以添加滑动开始的处理
    },

    // 结束滑动
    onPickerEnd() {
      // 可以添加滑动结束的处理
    },

    // 更新选中的地址
    updateSelectedAddress(provinceIndex, cityIndex, districtIndex) {
      const { addressData } = this.data;
      
      if (!addressData || !addressData[provinceIndex]) return;
      
      const province = addressData[provinceIndex];
      const city = province.c && province.c[cityIndex] ? province.c[cityIndex] : null;
      const district = city && city.c && city.c[districtIndex] ? city.c[districtIndex] : null;

      const selectedAddress = {
        province: province.n,
        city: city ? city.n : '',
        district: district ? district.n : '',
        province_id: province.v,
        city_id: city ? city.v : '',
        district_id: district ? district.v : ''
      };

      this.setData({
        selectedAddress
      });
    },

    // 取消选择
    onCancel() {
      this.triggerEvent('cancel');
    },

    // 确认选择
    onConfirm() {
      const value = this.data.tempValue;
      this.setData({
        pickerValue: value
      });
      
      this.updateSelectedAddress(value[0], value[1], value[2]);
      
      this.triggerEvent('confirm', {
        address: this.data.selectedAddress
      });
    },

    // 清除筛选
    onClearFilter() {
      this.triggerEvent('clear');
    },

    // 选择全国
    onSelectNational() {
      this.triggerEvent('national');
    },

    // 阻止触摸穿透
    preventTouchMove() {
      return false;
    }
  }
});

